package com.yvan.leto.server.security;

import com.yvan.leto.server.config.YvanSecurityProperties;
import com.yvan.leto.server.service.UserService;
import lombok.val;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

@Service
@EnableConfigurationProperties(YvanSecurityProperties.class)
public class HybJwtRealm extends AuthorizingRealm {

    private final YvanSecurityProperties securityProperties;
    private final UserService userService;

    @Autowired
    public HybJwtRealm(YvanSecurityProperties securityProperties,
                       UserService userService) {
        this.securityProperties = securityProperties;
        this.userService = userService;
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 当需要检测用户权限的时候调用此方法
     * 例如 checkRole,checkPermission
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        String jwtToken = principals.getPrimaryPrincipal().toString();
        simpleAuthorizationInfo.addRole(JwtHelper.getRole(jwtToken));

        return simpleAuthorizationInfo;
    }

    /**
     * 用户名正确与否
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String jwtToken = (String) auth.getCredentials();

        val loginName = JwtHelper.getLoginName(jwtToken);
        Long tokenVersion = userService.getTokenVersion(loginName);
        if (!JwtHelper.verify(jwtToken, loginName, tokenVersion, securityProperties.getSalt())) {
            throw new AuthenticationException("tokenVersion expire!");
        }

        return new SimpleAuthenticationInfo(jwtToken, jwtToken, "HybJwtRealm");
    }
}
